package com.wuxiaoge.service;

import com.wuxiaoge.dao.TaskDao;
import com.wuxiaoge.entity.Project;
import com.wuxiaoge.entity.Task;
import jakarta.annotation.Resource;
import jakarta.persistence.criteria.*;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
@Transactional(readOnly = true)
public class TaskService {

    @Resource
    TaskDao taskDao;


    /**
     * 复杂查询测试
     *
     * @param page
     * @param size
     * @return
     */
    public Page<Task> findBySepc(int page, int size) {

        PageRequest pageReq = this.buildPageRequest(page, size);
        Page<Task> tasks = this.taskDao.findAll(new MySpec(), pageReq);
        //传入了new MySpec() 既下面定义的匿名内部类 其中定义了查询条件
        return tasks;

    }

    /**
     * 建立分页排序请求
     *
     * @param page
     * @param size
     * @return
     */
    private PageRequest buildPageRequest(int page, int size) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        return PageRequest.of(page, size, sort);
    }

    /**
     * 建立查询条件
     */
    private class MySpec implements Specification<Task> {

        @Override
        public Predicate toPredicate(Root<Task> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

            //1.混合条件查询
//            Path<String> exp1 = root.get("taskName");
//            Path<Date>  exp2 = root.get("createTime");
//            Path<String> exp3 = root.get("taskDetail");
//            Predicate predicate = cb.and(cb.like(exp1, "%app%"),cb.lessThan(exp2, new Date()));
//            return cb.or(predicate,cb.equal(exp3, "kkk"));
//            return predicate;
           /* 类似的sql语句为:
            Hibernate:
                select
                    count(task0_.id) as col_0_0_
                from
                    tb_task task0_
                where
                    (
                        task0_.task_name like ?
                    )
                    and task0_.create_time<?
                    or task0_.task_detail=?
            */

            //2.多表查询
            Join<Task, Project> join = root.join("project", JoinType.INNER);
            Path<String> exp4 = join.get("projectName");
            return cb.like(exp4, "inve%");
//
//           /* Hibernate:
//            select
//                count(task0_.id) as col_0_0_
//            from
//                tb_task task0_
//            inner join
//                tb_project project1_
//                    on task0_.project_id=project1_.id
//            where
//                project1_.project_name like ?*/
//            return null ;
        }
    }
}
